<template>
  <div class="app-container home">
    <!-- 数据概览卡片 -->
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="stat-card">
          <div slot="header" class="clearfix">
            <span>今日销售额</span>
          </div>
          <div class="stat-value">¥{{this.animatedTodaySales}}</div>
          <div class="stat-change">
            <i :class="{'el-icon-arrow-up': isIncrease, 'el-icon-arrow-down': !isIncrease}"
               :style="{color: isIncrease ? '#67c23a' : '#f56c6c'}"></i>
            <span :class="{'increase': isIncrease, 'decrease': !isIncrease}">{{ formattedChangePercentage }}</span>
            <span class="text-gray">vs昨日</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div slot="header" class="clearfix">
            <span>订单数</span>
          </div>
          <div class="stat-value">{{this.animatedTodayOrders}}</div>
          <div class="stat-change">
            <i :class="{'el-icon-arrow-up': isIncreorder, 'el-icon-arrow-down': !isIncreorder}"
               :style="{color: isIncreorder ? '#67c23a' : '#f56c6c'}"></i>
            <span :class="{'increase': isIncreorder, 'decrease': !isIncreorder}">{{ OrderRatio }}</span>
            <span class="text-gray">vs昨日</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div slot="header" class="clearfix">
            <span>用户数</span>
          </div>
          <div class="stat-value">{{this.animatedUserNum}}</div>
          <div class="stat-change">
            <i class="el-icon-arrow-up" style="color: #67c23a"></i>
            <span class="increase"></span>
            <span class="text-gray"></span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div slot="header" class="clearfix">
            <span>商品数量</span>
          </div>
          <div class="stat-value">{{this.animatedGoodsSum}}</div>
          <div class="stat-change">
            <i class="el-icon-arrow-down" style="color: #f56c6c"></i>
            <span class="decrease"></span>
            <span class="text-gray"></span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 销售趋势和订单分析图表 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :sm="24" :lg="12">
        <el-card>
          <div slot="header" class="clearfix">
            <span>销售趋势分析</span>
            <el-radio-group size="small" v-model="salesTimeRange" class="float-right">
              <el-radio-button label="week">本周</el-radio-button>
              <el-radio-button label="month">本月</el-radio-button>
              <el-radio-button label="year">全年</el-radio-button>
            </el-radio-group>
          </div>
          <div id="salesTrendChart" style="width: 100%; height: 350px;"></div>
        </el-card>
      </el-col>
      <el-col :sm="24" :lg="12">
        <el-card>
          <div slot="header" class="clearfix">
            <span>订单状态分布</span>
          </div>
          <div id="orderStatusChart" style="width: 100%; height: 360px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 热门商品和地区销售排行 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :sm="24" :lg="12">
        <el-card>
          <div slot="header" class="clearfix">
            <span>热门商品销售排行</span>
          </div>
          <div id="productRankingChart" style="width: 100%; height: 350px;"></div>
        </el-card>
      </el-col>
      <el-col :sm="24" :lg="12">
        <el-card>
          <div slot="header" class="clearfix">
            <span>商品类型数量</span>
          </div>
          <div id="categoryPieChart" style="width: 100%; height: 350px;"></div>
        </el-card>
      </el-col>
    </el-row>
<!-- 最近订单表格 -->
    <!--
    <el-row style="margin-top: 20px;">
      <el-col :span="24">
        <el-card>
          <div slot="header" class="clearfix">
            <span>最近订单</span>
            <el-button style="float: right; padding: 3px 0" type="text">查看全部</el-button>
          </div>
          <el-table :data="orders" stripe style="width: 100%">
            <el-table-column prop="orderId" label="订单编号"></el-table-column>
            <el-table-column label="商品">
              <template slot-scope="scope">
                <img :src="scope.row.productImg" class="product-img" alt="商品图片">
                <span class="product-name">{{ scope.row.productName }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="username" label="客户名称"></el-table-column>
            <el-table-column prop="orderTime" label="下单时间"></el-table-column>
            <el-table-column prop="amount" label="金额"></el-table-column>
            <el-table-column prop="status" label="状态">
              <template slot-scope="scope">
                <el-tag :type="scope.row.statusType">{{ scope.row.status }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="handleOrder(scope.$index, scope.row)">查看</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row> -->
  </div>
</template>

<script>
import * as echarts from 'echarts';
import {
  getTodaySales,
  getYesterdaySales,
  getTodayOrders,
  getYesterdayOrders,
  getTotalUsers,
  getGoodsCount,
  getSalesTrend,
  getOrderStatus,
  getHotGoods,
  getGoodsType} from "@/api/home/home";
export default {
  data() {
    return {
      version: '3.8.8',
      salesTimeRange: 'week',
      orders: [
        {
          orderId: 'ORD-20240701001',
          productImg: 'https://picsum.photos/40/40?random=1',
          productName: '高级智能手表 Pro',
          username: '张三',
          orderTime: '2024-07-01 10:00:00',
          amount: '¥1,299.00',
          status: '已支付',
          statusType: 'success'
        },
        {
          orderId: 'ORD-20240701002',
          productImg: 'https://picsum.photos/40/40?random=2',
          productName: '无线蓝牙耳机',
          username: '李四',
          orderTime: '2024-07-01 09:30:00',
          amount: '¥399.00',
          status: '已发货',
          statusType: 'info'
        },
        {
          orderId: 'ORD-20240701003',
          productImg: 'https://picsum.photos/40/40?random=3',
          productName: '游戏手柄无线版',
          username: '王五',
          orderTime: '2024-07-01 08:45:00',
          amount: '¥249.00',
          status: '待发货',
          statusType: 'warning'
        },
        {
          orderId: 'ORD-20240701004',
          productImg: 'https://picsum.photos/40/40?random=4',
          productName: '机械键盘 RGB',
          username: '赵六',
          orderTime: '2024-07-01 07:15:00',
          amount: '¥499.00',
          status: '已完成',
          statusType: 'primary'
        },
        {
          orderId: 'ORD-20240701005',
          productImg: 'https://picsum.photos/40/40?random=5',
          productName: '高清摄像头',
          username: '钱七',
          orderTime: '2024-07-01 06:30:00',
          amount: '¥199.00',
          status: '已取消',
          statusType: 'danger'
        }
      ],

      // 新增动画中间值
      animatedTodaySales: 0,
      animatedTodayOrders: 0,
      animatedUserNum: 0,
      animatedGoodsSum: 0,

      TodaySales: 0, //今日销售额
      YesterdaySales: 0,//昨日销售额
      formattedChangePercentage: '0.00%', // 格式化后的百分比字符串
      isIncrease: true, // 是否增长

      TodayOrders: 0, //今日订单数
      YesterdayOrders: 0,//昨日订单数
      OrderRatio: '0.00%',//订单数百分比
      isIncreorder: true, //是否增长

      usernum : 0, //用户数量
      goodsnum : 0,//商品数量


    };
  },
  mounted() {
    this.$nextTick(() => {
        this.initSalesTrendChart();

        this.initOrderStatusChart();
        this.initProductRankingChart();
        this.initCategoryPieChart();
        window.addEventListener('resize', this.resizeCharts);
      });

  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeCharts);
  },
  created() {
    this.getList();
  },
  watch: {
    salesTimeRange: {
      handler(newVal) {
        this.initSalesTrendChart();
      },
      immediate: true // 初始化时立即执行
    }
  },
  methods: {
    //数据初始化
    getList(){
      //今日销售额数据
        getTodaySales().then(response => {
          this.TodaySales = response;
          console.log(this.TodaySales);
          // 当今日销售额和昨日销售额都获取到后，再计算百分比
          if (this.YesterdaySales) {
            this.calculateChangePercentage();
          }
          this.startAnimation(this.animatedTodaySales, this.TodaySales, 'animatedTodaySales');
        });

        //昨日销售额
        getYesterdaySales().then(response => {
          this.YesterdaySales = response;
          console.log(this.YesterdaySales);
          // 当今日销售额和昨日销售额都获取到后，再计算百分比
          if (this.TodaySales) {
            this.calculateChangePercentage();
          }
        });

        //今日订单数
        getTodayOrders().then(response => {
          this.TodayOrders = response;
          console.log(this.TodayOrders);
          // 当今日销售额和昨日销售额都获取到后，再计算百分比
          if (this.TodayOrders) {
            this.calculateOrder();
          }
          this.startAnimation(this.animatedTodayOrders, this.TodayOrders, 'animatedTodayOrders');
        });

        //昨日订单数
        getYesterdayOrders().then(response => {
          this.YesterdayOrders = response;
          console.log(this.YesterdayOrders);
          // 当今日销售额和昨日销售额都获取到后，再计算百分比
          if (this.YesterdayOrders) {
            this.calculateOrder();
          }
        });

        //用户数量
        getTotalUsers().then(response => {
          this.usernum = response;
          console.log(this.usernum);
          this.startAnimation(this.animatedUserNum, this.usernum, 'animatedUserNum');
        });

        //商品数量
        getGoodsCount().then(response => {
          this.goodsnum = response;
          console.log(this.goodsnum);
          this.startAnimation(this.animatedGoodsSum, this.goodsnum, 'animatedGoodsSum');
        });
    },
    // 通用动画方法
    startAnimation(startVal, targetVal, key) {
      let current = startVal;
      const duration = 500; // 动画总时长（毫秒）
      const step = Math.ceil(targetVal / (duration / 10)); // 每10ms递增的步长（数值越大，速度越快）

      const timer = setInterval(() => {
        if (current >= targetVal) {
          clearInterval(timer);
          this[key] = targetVal; // 确保最终值准确
          return;
        }
        current += step;
        if (current > targetVal) current = targetVal; // 防止超过目标值
        this[key] = current;
      }, 10); // 10ms更新一次数字
    },
    // 计算今昨两天销售额相差百分比
    calculateChangePercentage() {
      let percentage = 0;
      if (this.YesterdaySales !== 0) {
        percentage = ((this.TodaySales - this.YesterdaySales) / this.YesterdaySales) * 100;
      }
      // 格式化百分比为两位小数
      this.formattedChangePercentage = percentage.toFixed(2) + '%';
      // 判断是增长还是下降
      this.isIncrease = percentage >= 0;
      console.log('计算后销售额的百分比:', this.formattedChangePercentage);

    },
    calculateOrder(){
      let orderRdio = 0;
      if (this.YesterdayOrders !== 0) {
        orderRdio = ((this.TodayOrders - this.YesterdayOrders) / this.YesterdayOrders) * 100;
      }
      this.OrderRatio = orderRdio.toFixed(2) + '%';
      this.isIncreorder = orderRdio >= 0;
      console.log('计算后订单的百分比:', this.OrderRatio);
    },

    // 初始化销售趋势图表(折线图)
    async initSalesTrendChart() {
      try {
        const response = await getSalesTrend(this.salesTimeRange);
        // 假设后端直接返回数组（无data字段）
        const data = Array.isArray(response) ? response : [];
        console.log('销售趋势数据:', data); // 添加日志

        // 销毁旧实例
        if (this.salesTrendChart) {
          this.salesTrendChart.dispose();
        }

        // 初始化图表
        const salesTrendChart = echarts.init(document.getElementById('salesTrendChart'));
        this.salesTrendChart = salesTrendChart;

        // 修改xAxis映射逻辑（确保正确转换中文）
        const weekMap = {
          'Monday': '星期一',
          'Tuesday': '星期二',
          'Wednesday': '星期三',
          'Thursday': '星期四',
          'Friday': '星期五',
          'Saturday': '星期六',
          'Sunday': '星期日'
        };
        const xAxis = data.map(item => {
          const rawDate = item.date;
          return weekMap[rawDate] || rawDate; // 回退显示原始日期
        });
        const sales = data.map(item => Number(item.sales));
        const orders = data.map(item => Number(item.orders));

        // 动态计算y轴配置
        const maxSales = Math.max(...sales);
        const adjustedMaxSales = maxSales === 0 ? 1000 : Math.ceil(maxSales * 1.2);
        const maxOrders = Math.max(...orders);
        const adjustedMaxOrders = maxOrders === 0 ? 100 : Math.ceil(maxOrders * 1.2);

        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: { type: 'cross' }
          },
          legend: { data: ['销售额', '订单数'] },
          xAxis: {
            type: 'category',
            data: xAxis,
            axisLabel: { rotate: 45 }
          },
          yAxis: [
            {
              type: 'value',
              name: '销售额',
              min: 0,
              max: adjustedMaxSales, // 使用动态计算的最大值
              interval: Math.ceil(adjustedMaxSales / 5), // 自动计算刻度间隔
              axisLabel: { formatter: '¥{value}' }
            },
            {
              type: 'value',
              name: '订单数',
              min: 0,
              max: adjustedMaxOrders, // 使用动态计算的最大值
              interval: Math.ceil(adjustedMaxOrders / 5),
              axisLabel: { formatter: '{value} 单' }
            }
          ],
          series: [
            {
              name: '销售额',
              type: 'line',
              data: sales,
              yAxisIndex: 0,
              itemStyle: { color: '#409EFF' }
            },
            {
              name: '订单数',
              type: 'line',
              data: orders,
              yAxisIndex: 1,
              itemStyle: { color: '#E6A23C' }
            }
          ]
        };

        salesTrendChart.setOption(option);
      } catch (error) {
        console.error('图表错误:', error);
        this.$message.error('数据加载失败');
      }
    },

    // 初始化订单状态图表(饼图)
    async initOrderStatusChart() {
      try {
        const chartDom = document.getElementById('orderStatusChart');
        if (!chartDom) {
          console.error('图表容器未找到');
          return;
        }

        // 销毁旧实例
        if (this.orderStatusChart) {
          this.orderStatusChart.dispose();
        }

        // 初始化新实例
        this.orderStatusChart = echarts.init(chartDom);

        // 获取数据
        const response = await getOrderStatus();
        console.log('订单状态数据:', response);
        const chartData = response.map(item => ({
          value: item.count,
          name: item.status,
          itemStyle: { color: this.getStatusColor(item.status) }
        }));

        // 配置项
        const option = {
          tooltip: {
            trigger: 'item',
            formatter: '{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            data: chartData.map(d => d.name)
          },
          series: [{
            name: '订单状态',
            type: 'pie',
            radius: ['40%', '70%'],
            label: {
              show: true,
              position: 'inside',
              formatter: '{c}',
              color: '#fff',
              fontWeight: 'bold',
              textShadowColor: 'rgba(0,0,0,0.5)',
              textShadowBlur: 2,
              textShadowOffsetX: 1,
              textShadowOffsetY: 1
            },
            emphasis: {
              // label: {
              //   show: true,
              //   position: 'inside',
              //   formatter: '{b}\n{d}%',
              //   fontSize: 14,
              //   color: '#fff',
              //   textBorderColor: '#333',
              //   textBorderWidth: 2,
              //   fontWeight: 'bold'
              // }
            },
            labelLine: { show: false },
            data: chartData,
            avoidLabelOverlap: true
          }]
        };

        // 渲染图表
        this.orderStatusChart.setOption(option);
      } catch (error) {
        console.error('订单状态图表加载失败:', error);
      }
    },


    // 添加状态颜色映射方法
    getStatusColor(status) {
      const colorMap = {
        '已取消': '#909399',
        '已支付': '#67C23A',
        '待发货': '#F56C6C',
        '已发货': '#E6A23C',
        '已完成': '#409EFF'
      };
      return colorMap[status] || '#999';
    },

    // 初始化商品排行图表(横向柱状图)
    async initProductRankingChart() {
      try {
        const chartDom = document.getElementById('productRankingChart');
        if (this.productRankingChart) {
          this.productRankingChart.dispose();
        }
        this.productRankingChart = echarts.init(chartDom);

        // 获取数据
        const response = await getHotGoods();

        const processedData = response.map(item => ({
          ...item,
          sales: Number(item.sales) // 强制转换为数值类型
        }));
        const sortedData = processedData.sort((a, b) => b.sales - a.sales);// 新增排序
        console.log("ahjdhd"+sortedData);

        const products = sortedData.map(item => item.productName);
        const sales = sortedData.map(item => item.sales);

        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: { type: 'shadow' }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'value',
            axisLabel: {
              formatter: '{value}' // 可添加千分位格式化
            }
          },
          yAxis: {
            type: 'category',
            inverse: true,
            data: sortedData.map(item => item.productName),
            axisLabel: {
              interval: 0,
              formatter: function (value) { // 文本截断处理
                const maxLength = 15; // 最大显示字符数（含省略号）
                return value.length > maxLength ? value.slice(0, maxLength - 3) + '...' : value;
              },
              textOverflow: 'ellipsis', // 强制省略（部分场景需配合CSS）
              whiteSpace: 'nowrap',
              overflow: 'hidden'
            }
          },
          series: [{
            name: '销售量',
            type: 'bar',
            data: sortedData.map(item => item.sales),
            itemStyle: {
              color: '#409EFF',
              borderRadius: [0, 5, 5, 0] // 右侧圆角
            },
            label: {
              show: true,
              position: 'right',
              color: '#333',
              formatter: '{c}' // 显示具体数值
            }
          }]
        };

        this.productRankingChart.setOption(option);
      } catch (error) {
        console.error('商品排行图表加载失败:', error);
      }
    },


    async initCategoryPieChart() {
        try {
          const chartDom = document.getElementById('categoryPieChart');
          if (!chartDom) {
            console.error('图表容器未找到');
            return;
          }

          // 销毁旧实例
          if (this.categoryPieChart) {
            this.categoryPieChart.dispose();
          }

          // 初始化新实例
          this.categoryPieChart = echarts.init(chartDom);

          // 获取数据
          const response = await getGoodsType();
          console.log('商品类型数据:', response);

          // 处理数据格式
          const chartData = response.map(item => ({
            value: item.count,
            name: item.name
          }));

          // 配置项
          const option = {
            tooltip: {
              trigger: 'item',
              formatter: '{b}: {c} ({d}%)'
            },
            legend: {
              orient: 'vertical',
              left: 'left',
              data: chartData.map(d => d.name)
            },
            series: [{
              name: '商品类型',
              type: 'pie',
              radius: ['40%', '70%'],
              label: {
                show: true,
                position: 'inside',
                formatter: '{c}',
                color: '#fff',
                fontWeight: 'bold',
                textShadowColor: 'rgba(0,0,0,0.5)',
                textShadowBlur: 2,
                textShadowOffsetX: 1,
                textShadowOffsetY: 1
              },
              emphasis: {
                // label: {
                //   show: true,
                //   position: 'inside',
                //   formatter: '{b}\n{d}%',
                //   fontSize: 14,
                //   color: '#fff',
                //   textBorderColor: '#333',
                //   textBorderWidth: 2,
                //   fontWeight: 'bold'
                // }
              },
              labelLine: { show: false },
              data: chartData,
              avoidLabelOverlap: true
            }]
          };

          // 渲染图表
          this.categoryPieChart.setOption(option);
        } catch (error) {
          console.error('商品类型图表加载失败:', error);
        }
      },


    // 图表自适应窗口大小
    resizeCharts() {
      if (this.salesTrendChart) this.salesTrendChart.resize();
      if (this.orderStatusChart) this.orderStatusChart.resize();
      if (this.productRankingChart) this.productRankingChart.resize();
      if (this.categoryPieChart) this.categoryPieChart.resize();
    },

    // 处理订单查看
    handleOrder(index, row) {
      console.log('查看订单:', row);
      // 这里可以添加查看订单详情的逻辑
    },


  }
};
</script>

<style scoped>
.stat-card {
  height: 180px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

#salesTrendChart {
  width: 100%;
  height: 350px;
  min-height: 350px; /* 防止高度塌陷 */
}
.stat-value {
  font-size: 32px;
  font-weight: bold;
  margin: 10px 0;
}

.stat-change {
  display: flex;
  align-items: center;
}

.increase {
  color: #67c23a;
  margin: 0 5px;
}

.decrease {
  color: #f56c6c;
  margin: 0 5px;
}

.text-gray {
  color: #909399;
}

.product-img {
  width: 40px;
  height: 40px;
  margin-right: 10px;
  border-radius: 4px;
}

.product-name {
  display: inline-block;
  vertical-align: middle;
  max-width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
